// src/services/dao/LocalStorageWordDao.ts
import { type WordRecord  } from "../../types/WordResponse";
import type { WordDao } from "./WordDao";

const STORAGE_KEY = "words";
const CATEGORY_KEY = "words";


export class LocalStorageWordDao implements WordDao {
  addCategoryList(category: string): Promise<boolean> {
    let data = localStorage.getItem(CATEGORY_KEY);
    let categoryList: string[] = [];
    if(data!=null) {
      categoryList = JSON.parse(data);
    }
    categoryList.push(category);
    localStorage.setItem(CATEGORY_KEY, JSON.stringify(categoryList));
    return Promise.resolve(true)
  }
  getCategoryList(): Promise<string[]> {
    const data = localStorage.getItem(CATEGORY_KEY);
    if(data==null) {
      return Promise.resolve([]);
    }
    return Promise.resolve(JSON.parse(data));
  }
  async getAllWords(): Promise<WordRecord[]> {
    const data = localStorage.getItem(STORAGE_KEY);
    return data ? JSON.parse(data) : [];
  }

  async addOrUpdateWord(word: WordRecord): Promise<void> {
    const words = await this.getAllWords();
    const index = words.findIndex((w) => w.word === word.word);

    if (index !== -1) {
      // 更新现有单词
      words[index] = { ...words[index], ...word };
    } else {
      // 添加新单词
      words.push(word);
    }

    localStorage.setItem(STORAGE_KEY, JSON.stringify(words));
  }
}